package com.code.wordhelper.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

public class ClassUtils {
    private static final Logger logger = LoggerFactory.getLogger(ClassUtils.class);

    public static Object getFieldValue(Object obj, String fieldName) {
        try {
            fieldName = fieldName.trim();
            Field field = obj.getClass().getDeclaredField(fieldName);
            if (field == null) {
                return null;
            }
            field.setAccessible(true);
            return field.get(obj);
        } catch (Exception e) {
            logger.error("---" + fieldName);
            e.printStackTrace();
        }
        return fieldName;
    }

    public static List getCollectionFieldName(Object obj) {
        try {
            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field.getType().isAssignableFrom(List.class)) {
                    return (List) getFieldValue(obj, field.getName());
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param entity    对象
     * @param fieldName 对象中某属性名称
     * @return
     */
    public static boolean checkFields(Object entity, String fieldName) {
        try {
            Field[] fields = entity.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field.getName().equalsIgnoreCase(fieldName)) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    public static void main(String[] args) throws Exception {
//        OneLevelComponentResult detectionResult = new OneLevelComponentResult();
//
//        ComponentResult c1 = new ComponentResult();
//        c1.setName("---");
//        ComponentResult c2 = new ComponentResult();
//        c2.setName("---");
//        detectionResult.setComponentResults(Arrays.asList(c1, c2));
//        System.out.println(checkFields(c1, "weight"));

//        System.out.println(getCollectionFieldName(detectionResult));
//        DetectionPerson detectionPerson = new DetectionPerson();
//        detectionPerson.setUserId(1);
//        detectionPerson.setUsername("kkk");
//        detectionPerson.setRole("111");
//        detectionPerson.setRole2("222");
//
//        System.out.println(getFieldValue(detectionPerson, "username"));
//        System.out.println(getFieldValue(detectionPerson, "role"));
//        System.out.println(getFieldValue(detectionPerson, "role2"));
    }
}
